package org.beaconframework.ext.aws.typica;

import java.util.List;
import java.util.Map;

import org.beaconframework.util.exception.BeaconException;
import org.beaconframework.vaadin.util.VaadinContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyOverrideConfigurer;

import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.IndexedContainer;
import com.xerox.amazonws.sdb.Domain;
import com.xerox.amazonws.sdb.ItemAttribute;
import com.xerox.amazonws.sdb.QueryWithAttributesResult;
import com.xerox.amazonws.sdb.SDBException;
import com.xerox.amazonws.sdb.SimpleDB;

public class IndexedSimpleDbContainer extends IndexedContainer{

	Logger log = LoggerFactory.getLogger(IndexedSimpleDbContainer.class);
	private static final long serialVersionUID = 2094553325373095608L;
	TypicaClientFactory clientFactory;
	String queryString;
	
	public TypicaClientFactory getClientFactory() {
		if (clientFactory==null) {
			return VaadinContext.getBean("typicaClientFactory", TypicaClientFactory.class);
		}
		return clientFactory;
	}

	public void setClientFactory(TypicaClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	public void refresh() {
		try { 
			PropertyOverrideConfigurer pc;
			
			removeAllItems();
			System.out.println(getClientFactory());
			SimpleDB db = getClientFactory().createSimpleDBClient();
			System.out.println(db);
			Domain dom = db.getDomain("users");
			System.out.println(dom);
			String nextToken = null;
			int itemCount = 0;
			
			do {
				System.out.println("CONTAINER");
				QueryWithAttributesResult qwar = dom.selectItems(
						getQueryString(),
						nextToken);
				Map<String, List<ItemAttribute>> items = qwar.getItems();
				for (String id : items.keySet()) {
					System.out.println("Item : " + id);
					Object vidx = addItem();
					Item newItem = getItem(vidx);
					
					for (ItemAttribute attr : items.get(id)) {
						Property prop = newItem.getItemProperty(attr.getName());
						if (prop!=null && prop.getType()!=null) {
							log.debug("Setting {}={}",attr.getName(),attr.getValue());
							prop.setValue(attr.getValue());
						}
						else {
							log.debug("Not adding attribute '{}' because it was not declared",attr.getName());
						}
						System.out.println("  " + attr.getName() + " = "
								+ attr.getValue());
					}
					itemCount++;
				}
				nextToken = qwar.getNextToken();
				System.out.println("Box Usage :" + qwar.getBoxUsage());
				System.out.println(nextToken);
			} while (nextToken != null && !nextToken.trim().equals(""));
		} catch (SDBException e) {
			throw new BeaconException(e);
		}

		
	}

	public String getQueryString() {
		return queryString;
	}

	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}
}
